﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Data;
using QASampling.BusinessObject;
using QASampling.Util;
using QASampling.UI;
using System.Globalization;

namespace QASampling.QAControl
{
    public class QATextbox : System.Windows.Forms.TextBox
    {
        private System.Windows.Forms.ToolTip tooltip;
        private string errorMsg;
        private System.ComponentModel.IContainer components;

        private string originalValue = string.Empty;
        public string OriginalValue
        {
            get { return originalValue; }
            set { originalValue = value; SetBackgroundColor(); }
        }

        private JenisField fieldType;
        public JenisField FieldType
        {
            get { return fieldType; }
            set { fieldType = value; }
        }

        private string fieldRules;
        public string FieldRules
        {
            get { return fieldRules; }
            set { fieldRules = value; }
        }

        private string dateFormat;
        public string DateFormat
        {
            get { return dateFormat; }
            set { dateFormat = value; }
        }

        private string labelText;
        public string LabelText
        {
            get { return labelText; }
            set { labelText = value; }
        }

        private string fieldValue;
        public string FieldValue
        {
            get { return fieldValue; }
            set { fieldValue = value; }
        }

        private int digits = 0;
        public int Digits
        {
            get { return digits; }
            set { digits = value; }
        }

        private BaseFormSPTWithHeader form;
        public BaseFormSPTWithHeader Form
        {
            get { return form; }
            set { form = value; }
        }

        public string ErrorMsg
        {
            get { return errorMsg; }
        }

        public QATextbox()
        {
            InitializeComponent();
            // 
            // tooltip
            // 
            tooltip.AutoPopDelay = 1000;
            tooltip.InitialDelay = 1000;            
            tooltip.ReshowDelay = 500;
        }

        private void InitializeComponent()
        {
            this.tooltip = new System.Windows.Forms.ToolTip();
            this.SuspendLayout();
            // 
            // QATextbox
            // 
            this.TextChanged += new System.EventHandler(this.QATextbox_TextChanged);
            this.GotFocus += new System.EventHandler(this.QATextbox_GotFocus);
            this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.QATextbox_KeyPress);
            this.LostFocus += new System.EventHandler(this.QATextbox_LostFocus);
            this.MouseLeave += new System.EventHandler(this.QATextbox_MouseLeave);
            this.MouseHover += new System.EventHandler(this.QATextbox_MouseHover);
            this.Validating += new System.ComponentModel.CancelEventHandler(this.QATextbox_Validating);
            this.Layout += new System.Windows.Forms.LayoutEventHandler(QATextbox_Layout);
            this.ResumeLayout(false);

        }

        void QATextbox_Layout(object sender, System.Windows.Forms.LayoutEventArgs e)
        {
            if (this.fieldType == JenisField.Currency)
            {
                this.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
            }
        }

        void QATextbox_GotFocus(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(errorMsg))
            {
                tooltip.Show(string.Empty, this, 0);
                tooltip.SetToolTip(this, errorMsg);
                tooltip.Show(errorMsg, this, Width - 40, Height);
            }
        }

        void QATextbox_TextChanged(object sender, EventArgs e)
        {
            SetBackgroundColor();            
        }

        void QATextbox_MouseHover(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(errorMsg))
            {
                tooltip.Show(string.Empty, this, 0);
                tooltip.SetToolTip(this, errorMsg);
                tooltip.Show(errorMsg, this, 0, Height);
            }
        }

        void QATextbox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (fieldType == JenisField.Number)
            {
                if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
                    e.Handled = true;
            }
            else if (fieldType == JenisField.Currency)
            {
                if ((Char.IsDigit(e.KeyChar) || Char.IsControl(e.KeyChar))) 
                {
                       
                }
                else if (e.KeyChar == '.' || e.KeyChar == ',' || e.KeyChar == '-' || e.KeyChar == '(' || e.KeyChar == ')') 
                {
                    
                }
                else
                    e.Handled = true;
            }
            else if (fieldType == JenisField.Datetime)
            {
                if ((Char.IsDigit(e.KeyChar) || Char.IsControl(e.KeyChar))) { }
                else if (e.KeyChar == '-') { }
                else
                    e.Handled = true;
            }

            SetBackgroundColor();
        }

        void QATextbox_LostFocus(object sender, EventArgs e)
        {
            tooltip.Hide(this);      
            if (fieldType == JenisField.Currency)
            {
                string value = this.Text;
                if (!ReadOnly)
                {
                    if (ValidationUtil.IsValidCurrency(false, this.Text, ref value, false))
                    {
                        decimal rounding = 1000;
                        if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["RoundingValue"]))
                        {
                            decimal.TryParse(System.Configuration.ConfigurationManager.AppSettings["RoundingValue"], out rounding);
                        }
                        value = ValidationUtil.RoundingUpTo(value, digits, rounding);

                        decimal d = Convert.ToDecimal(value);
                        string numericFormat = "N" + digits;
                        this.Text = d.ToString(numericFormat, CultureInfo.GetCultureInfo("id-ID"));                        
                    }
                }
            }        
            //SetBackgroundColor();                       
        }

        private void SetBackgroundColor()
        {
            if (this.OriginalValue != this.Text)
                BackColor = Color.LightGreen;
            else if (!string.IsNullOrEmpty(errorMsg))
                BackColor = Color.Red;
            else
                BackColor = Color.White;
        }

        private void QATextbox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                errorMsg = string.Empty;
                if (this.FindForm() != null)
                {
                    if (!ValidationUtil.CalculateFieldsMathExp(this, this.fieldRules, ref errorMsg))
                    {
                        BackColor = Color.Red;
                        e.Cancel = false;
                        QAFieldErrorMsg fem = new QAFieldErrorMsg();
                        //fem.DocId = QAController.DocId;
                        fem.Field = this.LabelText;
                        fem.ErrorMsg = errorMsg;
                        if (QAController.FieldErrorMsg.IndexOf(fem) < 0)
                            QAController.FieldErrorMsg.Add(fem);
                        tooltip.Show(string.Empty, this, 0);
                        tooltip.SetToolTip(this, errorMsg);
                        tooltip.Show(errorMsg, this, Width - 40, Height, 2000);
                    }
                    else
                    {
                        e.Cancel = false;
                        errorMsg = string.Empty;
                        SetBackgroundColor();

                        if (fieldType.Equals(JenisField.Datetime))
                        {
                            if (!String.IsNullOrEmpty(Text) && !ValidationUtil.IsValidDate(Text, dateFormat))
                            {
                                BackColor = Color.Red;
                                errorMsg += " Masukkan penanggalan dengan benar " + dateFormat;
                                QAFieldErrorMsg fem = new QAFieldErrorMsg();
                                //fem.DocId = QAController.DocId;
                                fem.Field = this.LabelText;
                                fem.ErrorMsg = errorMsg;
                                tooltip.Show(string.Empty, this, 0);
                                tooltip.SetToolTip(this, errorMsg);
                                tooltip.Show(errorMsg, this, Width - 40, Height, 2000);
                            }
                        }
                        else if (fieldType.Equals(JenisField.Currency))
                        {
                            if (!ValidationUtil.IsValidCurrency(Text, true))
                            {
                                BackColor = Color.Red;
                                errorMsg += " Masukkan penulisan uang dengan benar";
                                QAFieldErrorMsg fem = new QAFieldErrorMsg();
                                //fem.DocId = QAController.DocId;
                                fem.Field = this.LabelText;
                                fem.ErrorMsg = errorMsg;
                                tooltip.Show(string.Empty, this, 0);
                                tooltip.SetToolTip(this, errorMsg);
                                tooltip.Show(errorMsg, this, Width - 40, Height, 2000);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // throw ex;
            }
        }

        private void QATextbox_MouseLeave(object sender, EventArgs e)
        {
            tooltip.Hide(this);
        }
    }
}
